<template>
    <div class="container">
        <header-nav/>
        <el-dialog title="修改基本信息" :visible.sync="setForm">
            <el-form :model="form" status-icon :rules="rules" ref="baseForm">
                <el-form-item label="昵称" :label-width="formLabelWidth">
                    <el-input disabled v-model="form.name" autocomplete="off"></el-input>
                    <span style="color: #f00;font-size: 12px">*昵称不可修改</span>
                </el-form-item>
                <el-form-item prop="phone" label="手机号码" :label-width="formLabelWidth">
                    <el-input v-model="form.phone" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="setForm = false">取 消</el-button>
                <el-button type="primary" @click="saveSetting('baseForm')"
                           v-loading.fullscreen.lock="fullscreenLoading">
                    修改
                </el-button>
            </div>
        </el-dialog>

        <el-dialog title="修改密码" :visible.sync="setPass">
            <el-form :model="passForm" status-icon :rules="rules" ref="passForm">
                <el-form-item prop="oldPass" label="旧密码" :label-width="formLabelWidth">
                    <el-input type="password" v-model="passForm.oldPass" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="newPass" label="新密码" :label-width="formLabelWidth">
                    <el-input type="password" v-model="passForm.newPass" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="checkPass" label="确认密码" :label-width="formLabelWidth">
                    <el-input type="password" v-model="passForm.checkPass" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="setPass = false">取 消</el-button>
                <el-button type="primary" @click="savePass('passForm')">修改</el-button>
            </div>
        </el-dialog>

        <div class="content-wrapper">
            <div class="left-side">
                <div class="user-wrapper">
                    <div class="avatar">
                        <img src="@/assets/styles/images/avatar2.jpg" alt="">
                    </div>
                    <p class="nickname"> {{ this.$store.state.userInfo.username}} </p>
                    <div class="btn-wrapper">
                        <div class="setting" @click="changeSetting">
                            <span>修改基本信息</span>
                        </div>
                        <div class="change-pass" @click="changePass">
                            <span>修改密码</span>
                        </div>
                        <div class="quit" @click="quit">
                            <span>退出</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="right-side border">
                <el-tabs v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="我的发布" name="first">
                        <div class="nothing" v-if="!noArticle">
                            <img src="@/assets/styles/images/nocomment.png" alt="">
                            <p>暂时没有发布任何内容噢～</p>
                        </div>
                        <div class="post-list" v-if="noArticle">
                            <div class="post-item border-bottom" v-for="item in postList" :key="item.id">
                                <div class="post-img">
                                    <img src="@/assets/styles/images/post-img4.jpg" alt="">
                                </div>
                                <div class="post-details" @click="goDetail(item.id)">
                                    <div class="post-title">
                                        <span>{{ item.title }}</span>
                                    </div>
                                    <div class="post-desc">
                                        <span>{{ item.desc }}</span>
                                    </div>
                                </div>
                                <div class="act-btn">
                                    <div class="edit_btn">
                                        <el-button size="mini" round @click="editArticle(item.id)">修改</el-button>
                                    </div>
                                    <div class="del_btn">
                                        <el-button type="danger" size="mini" round @click="delArticle(item.id)">删除
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="我的评论" name="second">
                        <div class="nothing" v-if="noComment">
                            <img src="@/assets/styles/images/nocomment.png" alt="">
                            <p>暂时没有发布任何评论噢～</p>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="我的收藏" name="third">
                        <div class="nothing" v-if="noSave">
                            <img src="@/assets/styles/images/nocomment.png" alt="">
                            <p>暂时没有收藏任何内容噢～</p>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
    </div>
</template>

<script>
    import HeaderNav from '@/components/HeaderNavbar'
    import {getDataByList, getDataById, del} from "@/api/article";
    import {changeBase, changePassword} from "@/api/user";
    import {mapMutations} from 'vuex';

    export default {
        name: "PersonalPage",
        data() {
            var checkPhone = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('手机号码不能为空'));
                }
                setTimeout(() => {
                    if (typeof Number.isInteger(value) != Number) {
                        if (value.length != 11) {
                            callback(new Error('手机格式错误'));
                        } else {
                            callback();
                        }
                    }
                }, 1000);
            };
            var checkOldPass = (rule, value, callback) => {
                console.log(value);
                if (!value) {
                    return callback(new Error('旧密码不能为空'));
                }
                callback();
            };
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.passForm.newPass !== '') {
                        this.$refs.passForm.validateField('checkPass');
                    }
                    callback();
                }
            };
            var checkPass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.passForm.newPass) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                fullscreenLoading: false,
                activeName: 'first',
                postList: [],
                noArticle: true,
                noComment: true,
                noSave: true,
                currentEdit: [],
                form: {
                    id: this.$store.state.userInfo.id,
                    name: this.$store.state.userInfo.username,
                    phone: this.$store.state.userInfo.phone
                },
                passForm: {
                    id: this.$store.state.userInfo.id,
                    oldPass: '',
                    newPass: '',
                    checkPass: ''
                },
                setForm: false,
                setPass: false,
                formLabelWidth: '120px',
                rules: {
                    phone: [
                        {validator: checkPhone, trigger: 'blur'}
                    ],
                    oldPass: [
                        {validator: checkOldPass, trigger: 'blur'}
                    ],
                    newPass: [
                        {validator: validatePass, trigger: 'blur'}
                    ],
                    checkPass: [
                        {validator: checkPass, trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            ...mapMutations(['saveItem']),
            // 修改基本信息按钮
            changeSetting() {
                this.setForm = true
            },
            //  提交修改基本信息
            saveSetting(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let datas = {
                            'id': this.form.id,
                            'phone': this.form.phone
                        }
                        changeBase(datas).then(res => {
                            console.log(res)
                            this.fullscreenLoading = true;
                            setTimeout(() => {
                                this.fullscreenLoading = false;
                                this.$notify({
                                    title: '成功',
                                    message: '修改成功',
                                    type: 'success'
                                });
                                setTimeout(() => {
                                    /* 清除用户信息，重新登录*/
                                    localStorage.removeItem('isLogin')
                                    localStorage.removeItem('userToken')
                                    localStorage.removeItem('userInfo')
                                    this.$notify({
                                        title: '提示',
                                        message: '用户信息失效，请重新登录',
                                        type: 'warning'
                                    });
                                    this.$router.push('/login')
                                }, 1000)
                            }, 1000);
                            this.setForm = false
                        }).catch(err => {
                            console.log(err);
                        })
                    }
                })

            },
            //  修改密码
            changePass() {
                this.setPass = true
                this.passForm.id = this.$store.state.userInfo.id
                this.passForm.oldPass = ''
                this.passForm.newPass = ''
                this.passForm.checkPass = ''
            },
            //  提交修改密码
            savePass(formName) {
                let datas = {
                    'id': this.passForm.id,
                    'oldPass': this.passForm.oldPass,
                    'newPass': this.passForm.newPass
                };
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        changePassword(datas).then(res => {
                            if (res.data.code === '40005') {
                                this.$message({
                                    message: '旧密码有误',
                                    tpye: 'warning'
                                })
                            }
                            if (res.data.code === '20003') {
                                this.fullscreenLoading = true;
                                setTimeout(() => {
                                    this.fullscreenLoading = false;
                                    this.$notify({
                                        title: '成功',
                                        message: '修改成功',
                                        type: 'success'
                                    });
                                    this.setPass = false
                                    setTimeout(() => {
                                        /* 清除用户信息，重新登录*/
                                        localStorage.removeItem('isLogin')
                                        localStorage.removeItem('userToken')
                                        localStorage.removeItem('userInfo')
                                        this.$notify({
                                            title: '提示',
                                            message: '用户信息失效，请重新登录',
                                            type: 'warning'
                                        });
                                        this.$router.push('/login')
                                    }, 1000)
                                }, 1000);
                            }
                        }).catch(err => {
                            console.log(err);
                        })
                    }
                })
            }
            ,
            handleClick(tab, event) {
                console.log(tab, event);
            }
            ,
            //  查看文章详情
            goDetail(id) {
                getDataById(id).then(res => {
                    let data = res.data;
                    this.saveItem({value: data})
                });
                this.$router.push('/details/' + id)
            }
            ,
            //  修改文章按钮
            editArticle(id) {
                getDataById(id).then(res => {
                    let data = res.data
                    this.currentEdit = data
                    this.saveItem({value: data})
                    this.$router.push('/edit/' + id)
                }).catch(err => {
                    console.log(err);
                })
            }
            ,
            //  删除文章
            delArticle(id) {
                this.$confirm('此操作将退出账号, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    del(id).then(res => {
                        console.log(res)
                    }).catch(err => {
                        console.log(err)
                    })
                    const loading = this.$loading({
                        lock: true,
                        text: '删除中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    setTimeout(() => {
                        loading.close();
                        this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getArticle()
                    }, 700);
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '我知道你舍不得离开～'
                    });
                });
            }
            ,
            //   获取文章
            getArticle() {
                getDataByList().then(res => {
                    this.postList = res.data.data;
                }).catch(err => {
                    console.log(err);
                })
            }
            ,
            //  退出登录
            quit() {
                localStorage.removeItem('userToken');
                localStorage.removeItem('isLogin');
                this.$confirm('此操作将会退出登录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$router.push('/login');
                    this.$message({
                        type: 'success',
                        message: '退出成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '我知道你舍不得离开～'
                    });
                });
            }
        },
        components: {
            HeaderNav
        }
        ,
        mounted() {
            this.getArticle();
        }
        ,
        watch: {
            '$route'(to, from) {
                if (from.name === 'Edit' || from.name === 'Add') {
                    this.getArticle()
                }
            }
        }
    }
</script>

<style lang="stylus" scoped>
    @import "~@/assets/styles/css/variable.styl"
    .content-wrapper
        display: flex;
        padding: 2% 14%;
        .left-side
            flex: 2;
            .user-wrapper
                background: #fff;
                box-shadow: 0 0 10px 5px #eaeaea;
                .avatar
                    width: 30%;
                    padding: 10% 35%;
                    img
                        width: 100%;
                        border-radius: 50%;
                .nickname
                    text-align: center;
                    margin: 10px 0;
                    padding: 0;
                .btn-wrapper
                    padding: 2px 25% 25px;
                    .setting, .change-pass, .quit
                        width: 100%;
                        text-align: center;
                        color: #fff;
                        padding: 10px 0;
                        margin: 15px 0;
                        font-size: 14px;
                    .setting
                        background: #009688;
                        &:hover
                            cursor: pointer;
                            background: #25a79b
                    .change-pass
                        background: #d86969;
                        &:hover
                            cursor: pointer;
                            background: #d68888
                    .quit
                        background: $themeColor;
                        &:hover
                            cursor: pointer;
                            background #dc8369
        .right-side >>> ul li
            &:hover
                background-color: #eaeaea !important;
                color: $themeColor !important;
        .right-side >>> .el-tabs.el-tabs--top
            padding: 5px 15px;
        .right-side >>> .el-tabs__item
            font-size: 12px;
            color: #555;
            &:hover
                color: $themeColor;

        .right-side >>> .is-active
            color: $themeColor;
        .right-side >>> .el-tabs__active-bar
            background-color: $themeColor;
        .right-side
            flex: 5;
            margin-left: 10px;
            box-shadow: 0 0 10px 5px #f1f1f1;
            .nothing
                width: 50%;
                padding: 30px 25%;
                img
                    width: 100%;
                p
                    margin: 8px;
                    text-align: center;
                    color: #999;
                    font-size: 12px;
            .post-list
                border: 1px solid #f9f9f9;
                box-shadow: 0 0 10px 5px #f5f5f5;
                .post-item
                    display: flex;
                    width: 100%;
                    background: #fff;
                    padding: 10px 0;
                    .post-img
                        width: 12%;
                        padding: 5px 10px 0;
                        img
                            width: 100%;
                    .post-details
                        width: 65%;
                        margin-left: 10px;
                        .post-title
                            font-size: 16px;
                            font-weight: 600;
                            color: #333;
                            padding: 15px 0;
                            &:hover
                                color: $themeColor;
                                cursor: pointer;
                        .post-desc
                            font-size: 12px;
                            color: #afafaf;
                            font-weight: 400;
                            width: 370px;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                    .act-btn
                        width: 25%;
                        display: flex;
                        line-height: 70px;
                        .edit_btn
                            margin-right: 10px

</style>